package com.inkrl.payment.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inkrl.payment.mapper.PaymentMapper;
import com.jt.common.pojo.CartItem;
import com.jt.common.pojo.Order;
import com.jt.common.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Autowired(required = false)
    private PaymentMapper paymentMapper;
    private StringRedisTemplate template;
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public Order payment(String address,String phone,String receiver,String product,String count,String token) {
        ValueOperations<String,String> ospValue = template.opsForValue();
        String userJson = ospValue.get(token);
        try {
            User user = mapper.readValue(userJson,User.class);
            Order order = new Order();
            order.setPlaced(new Date());
            order.setPhone(phone);
            order.setAddress(address);
            order.setReceiver(receiver);
            paymentMapper.updateByOrderId(order);
            CartItem cartItem = new CartItem();
            cartItem.setCount(Integer.parseInt(count));
            cartItem.setProduct(product);
            cartItem.setUser_id(user.getPhone());
            paymentMapper.deleteByCountandProductandUserid(cartItem);
            return order;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
